import Flutter
import Foundation
import UIKit

public class ApplicationStateHandler: NSObject {
    private var statusChannel: FlutterMethodChannel?
    
    public func setup(messenger: FlutterBinaryMessenger) {
        statusChannel = FlutterMethodChannel(name: "com.cqxm.app/BusinessKitChannel", binaryMessenger: messenger)
        
        // 注册通知监听
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(applicationDidBecomeActive),
            name: UIApplication.didBecomeActiveNotification,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(applicationDidEnterBackground),
            name: UIApplication.didEnterBackgroundNotification,
            object: nil
        )
    }
    
    @objc private func applicationDidBecomeActive() {
        sendApplicationDidBecomeActiveToFlutter()
    }
    
    @objc private func applicationDidEnterBackground() {
        sendApplicationDidEnterBackgroundToFlutter()
    }
    
    // 向Flutter发送APP已经变为活跃状态
    private func sendApplicationDidBecomeActiveToFlutter() {
        DispatchQueue.main.async { [weak self] in
            self?.statusChannel?.invokeMethod(
                "applicationDidBecomeActive",
                arguments: [:]
            )
        }
    }
    
    // 向Flutter发送APP已经进入后台
    private func sendApplicationDidEnterBackgroundToFlutter() {
        DispatchQueue.main.async { [weak self] in
            self?.statusChannel?.invokeMethod(
                "applicationDidEnterBackground",
                arguments: [:]
            )
        }
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
